﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.FileServer.Core.Object;
using Kingdee.BOS.FileServer.ProxyService;
using Kingdee.BOS.JSON;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;

namespace WSDZ.KM.ZH.SuitPrintCompressPicture
{
    [Description("(表单)套打压缩图片"), HotUpdate]
    public class SuitPrintCompressPicture : AbstractDynamicFormPlugIn
    {
        //private static string EntryKey = "F_RLKX_XSDDMXZZD";
        //private static string PictureDynamicFieldKey = "picture";//动态字段标识
        //private static string PictureBingKey = "FNewPicture";//图片附件 bindField 的值(可以导出套打，编辑后，再导入 目前bos无法直接编辑)
        private static string EntryKey = "";
        private static string PictureDynamicFieldKey = "";//动态字段标识
        private static string PictureBingKey = "";//图片附件 bindField 的值(可以导出套打，编辑后，再导入 目前bos无法直接编辑)
        private static int Height = 0;
        private static int Width = 0;
        public override void OnInitialize(InitializeEventArgs e)
        {
            base.OnInitialize(e);
            string formId = View.BillBusinessInfo.GetForm().Id;
            string sql = $@"/*dialect*/ select top 1
EntryKey=enty.FENTRYKEY
,PictureDynamicFieldKey=enty.FDYNAMICFIELDKEY
,PictureBingKey=enty.FBINGFIELDKEY
,Height=enty.FHeight
,Width=enty.FWidth
from TPrintPictureConfigEntry enty
left join TPrintPictureConfig main on enty.FID=main.FID
where main.FDOCUMENTSTATUS='C'
and ISNULL(main.FFORBIDSTATUS,'')='A'
and enty.FISFORBID=0
and enty.FBillKey='{formId}'";
            DynamicObjectCollection datas = DBUtils.ExecuteDynamicObject(Context,sql);
            if (datas!=null&&datas.Count>0)
            {
                DynamicObject obj = datas[0];
                EntryKey = obj["EntryKey"].ToStringV1();
                PictureDynamicFieldKey = obj["PictureDynamicFieldKey"].ToStringV1();
                PictureBingKey = obj["PictureBingKey"].ToStringV1();
                Height = obj["Height"].ToStringV1().ToInt32V1();
                Width = obj["Width"].ToStringV1().ToInt32V1();
            }
        }
        public override void OnPrepareNotePrintData(PreparePrintDataEventArgs e)
        {
            base.OnPrepareNotePrintData(e);
            if (EntryKey.IsNullOrEmptyOrWhiteSpace()|| PictureDynamicFieldKey.IsNullOrEmptyOrWhiteSpace() || PictureBingKey.IsNullOrEmptyOrWhiteSpace()|| Height==0||Width==0)
                return;
            if (!e.DataSourceId.ToStringV1().EqualsV1(EntryKey))
                return;
            var objType = e.DynamicObjectType;
            if (!objType.Properties.ContainsKey(PictureDynamicFieldKey))
                return;
            if (!objType.Properties.ContainsKey(PictureBingKey))
                objType.RegisterProperty(PictureBingKey, typeof(byte[]));
            int idx = 0;
            foreach (DynamicObject dataObj in e.DataObjects)
            {
                idx++;
                string picturnId = dataObj[PictureDynamicFieldKey].ToStringV1();
                if (picturnId.IsNullOrEmptyOrWhiteSpace())
                    continue;
                var newObj = new DynamicObject(objType);

                TFileInfo tFile = new TFileInfo() { FileId = picturnId, CTX = View.Context };
                UpDownloadService fileService = new UpDownloadService();
                byte[] fileData = fileService.GetFileData(tFile);
                Bitmap bmp = ToImage(fileData);

                if (bmp.Height > Height)
                {
                    Bitmap bmp1 = ZoomImage(bmp, Height, Width);
                    byte[] fileData1 = ImageToByte(bmp1);
                    foreach (var prop in dataObj.DynamicObjectType.Properties)
                        newObj[prop] = dataObj[prop];
                    newObj[PictureBingKey] = fileData1;
                    e.DataObjects[idx - 1] = newObj;
                }
                else
                {
                    foreach (var prop in dataObj.DynamicObjectType.Properties)
                        newObj[prop] = dataObj[prop];
                    newObj[PictureBingKey] = fileData;
                    e.DataObjects[idx - 1] = newObj;
                }
            
             

            }
        }






        /// <summary>
        /// 等比例缩放图片
        /// </summary>
        /// <param name="bitmap">图片</param>
        /// <param name="destHeight">高度</param>
        /// <param name="destWidth">宽度</param>
        /// <returns></returns>
        private Bitmap ZoomImage(Bitmap bitmap, int destHeight, int destWidth)
        {
            try
            {
                System.Drawing.Image sourImage = bitmap;
                if (sourImage.Height<= destHeight)
                {
                    return bitmap;
                }
                int width = 0, height = 0;
                //按比例缩放
                int sourWidth = sourImage.Width;
                int sourHeight = sourImage.Height;
                if (sourHeight > destHeight || sourWidth > destWidth)
                {
                    if ((sourWidth * destHeight) > (sourHeight * destWidth))
                    {
                        width = destWidth;
                        height = (destWidth * sourHeight) / sourWidth;
                    }
                    else
                    {
                        height = destHeight;
                        width = (sourWidth * destHeight) / sourHeight;
                    }
                }
                else
                {
                    width = sourWidth;
                    height = sourHeight;
                }
                Bitmap destBitmap = new Bitmap(destWidth, destHeight);
                Graphics g = Graphics.FromImage(destBitmap);
                g.Clear(Color.Transparent);
                //设置画布的描绘质量
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.DrawImage(sourImage, new Rectangle((destWidth - width) / 2, (destHeight - height) / 2, width, height), 0, 0, sourImage.Width, sourImage.Height, GraphicsUnit.Pixel);
                g.Dispose();
                //设置压缩质量
                System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
                long[] quality = new long[1];
                quality[0] = 100;
                System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                encoderParams.Param[0] = encoderParam;
                sourImage.Dispose();
                return destBitmap;
            }
            catch
            {
                return bitmap;
            }
        }

        private Bitmap ToImage(byte[] arr)
        {
            try
            {
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);
                ms.Close();
                return bmp;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                return null;
            }
        }

        public byte[] ImageToByte(Bitmap bmp)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, ImageFormat.Png);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                return arr;
            }
            catch (Exception ex)
            {
                return new byte[0] ;
            }
        } 

    }
}
